package com.xunmall.account.service.impl;

import com.xunmall.account.entity.ApiDO;
import com.xunmall.account.mapper.ApiMapper;
import com.xunmall.account.service.ApiService;
import com.xunmall.base.exception.BadRequestException;
import com.xunmall.base.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Service
public class ApiServiceImpl implements ApiService {
    @Autowired
    ApiMapper apiMapper;

    @Override
    public ApiDO create(ApiDO entity) {
        if (entity == null || StringUtils.isBlank(entity.getUrl())) {
            throw new BadRequestException("error.account.0001", this);
        }
        entity.buildForInsert();
        int result = apiMapper.insertSelective(entity);
        if (result > 0) {
            return apiMapper.selectByPrimaryKey(entity.getUuid());
        } else {
            throw new BadRequestException("error.account.0002", this);
        }
    }

    @Override
    public ApiDO update(ApiDO entity) {
        if (entity == null || StringUtils.isBlank(entity.getUuid())) {
            throw new BadRequestException("error.account.0001", this);
        }
        ApiDO oldEntity = apiMapper.selectByPrimaryKey(entity.getUuid());
        if (oldEntity == null) {
            throw new BadRequestException("error.account.0003", this);
        }
        BeanUtils.copyProperties(entity, oldEntity);
        oldEntity.buildForUpdate();
        int result = apiMapper.updateByPrimaryKeySelective(oldEntity);
        if (result > 0) {
            return apiMapper.selectByPrimaryKey(oldEntity.getUuid());
        } else {
            throw new BadRequestException("error.account.0002", this);
        }
    }

    @Override
    public ApiDO getApiByUuid(String uuid) {
        return apiMapper.selectByPrimaryKey(uuid);
    }
}